<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import OrderRegistrationModal from './OrderRegistrationModal.vue'

const showModal = ref(false)
const modalContent = ref('')
let socket
const router = useRouter()
const route = useRoute()

const globalTasks = ref([
  // 年初计划
  { name: '新年度规划会议', checked: false, module: 'annual' },
  { name: '参加订货会/广告投放', checked: false, module: 'annual' },
  { name: '参加订货会/登记销售订单', checked: false, module: 'annual' },
  { name: '制定新年度计划', checked: false, module: 'annual' },
  { name: '支付应付税', checked: false, module: 'annual' },
  // 1季度进度
  { name: '1季度：特殊贷款(高利贷款)', checked: false, module: 'quarter1' },
  { name: '1季度：更新短期贷款/支付利息/获得新的贷款', checked: false, module: 'quarter1' },
  { name: '1季度：原材料入库/更新原料订单', checked: false, module: 'quarter1' },
  { name: '1季度：下原料订单', checked: false, module: 'quarter1' },
  { name: '1季度：更新生产/完工入库', checked: false, module: 'quarter1' },
  { name: '1季度：变卖生产线', checked: false, module: 'quarter1' },
  { name: '1季度：投资新生产线/再投生产线/生产线转产', checked: false, module: 'quarter1' },
  { name: '1季度：开始新的生产', checked: false, module: 'quarter1' },
  { name: '1季度：更新应收款/应收款收现', checked: false, module: 'quarter1' },
  { name: '1季度：交货给客户', checked: false, module: 'quarter1' },
  { name: '1季度：产品研发投资', checked: false, module: 'quarter1' },
  { name: '1季度：支付行政管理费用', checked: false, module: 'quarter1' },

  // 2季度进度
  { name: '2季度：特殊贷款(高利贷款)', checked: false, module: 'quarter2' },
  { name: '2季度：更新短期贷款/支付利息/获得新的贷款', checked: false, module: 'quarter2' },
  { name: '2季度：原材料入库/更新原料订单', checked: false, module: 'quarter2' },
  { name: '2季度：下原料订单', checked: false, module: 'quarter2' },
  { name: '2季度：更新生产/完工入库', checked: false, module: 'quarter2' },
  { name: '2季度：变卖生产线', checked: false, module: 'quarter2' },
  { name: '2季度：投资新生产线/再投生产线/生产线转产', checked: false, module: 'quarter2' },
  { name: '2季度：开始新的生产', checked: false, module: 'quarter2' },
  { name: '2季度：更新应收款/应收款收现', checked: false, module: 'quarter2' },
  { name: '2季度：交货给客户', checked: false, module: 'quarter2' },
  { name: '2季度：产品研发投资', checked: false, module: 'quarter2' },
  { name: '2季度：支付行政管理费用', checked: false, module: 'quarter2' },

  // 3季度进度
  { name: '3季度：特殊贷款(高利贷款)', checked: false, module: 'quarter3' },
  { name: '3季度：更新短期贷款/支付利息/获得新的贷款', checked: false, module: 'quarter3' },
  { name: '3季度：原材料入库/更新原料订单', checked: false, module: 'quarter3' },
  { name: '3季度：下原料订单', checked: false, module: 'quarter3' },
  { name: '3季度：更新生产/完工入库', checked: false, module: 'quarter3' },
  { name: '3季度：变卖生产线', checked: false, module: 'quarter3' },
  { name: '3季度：投资新生产线/再投生产线/生产线转产', checked: false, module: 'quarter3' },
  { name: '3季度：开始新的生产', checked: false, module: 'quarter3' },
  { name: '3季度：更新应收款/应收款收现', checked: false, module: 'quarter3' },
  { name: '3季度：交货给客户', checked: false, module: 'quarter3' },
  { name: '3季度：产品研发投资', checked: false, module: 'quarter3' },
  { name: '3季度：支付行政管理费用', checked: false, module: 'quarter3' },

  // 4季度进度
  { name: '4季度：特殊贷款(高利贷款)', checked: false, module: 'quarter4' },
  { name: '4季度：更新短期贷款/支付利息/获得新的贷款', checked: false, module: 'quarter4' },
  { name: '4季度：原材料入库/更新原料订单', checked: false, module: 'quarter4' },
  { name: '4季度：下原料订单', checked: false, module: 'quarter4' },
  { name: '4季度：更新生产/完工入库', checked: false, module: 'quarter4' },
  { name: '4季度：变卖生产线', checked: false, module: 'quarter4' },
  { name: '4季度：投资新生产线/再投生产线/生产线转产', checked: false, module: 'quarter4' },
  { name: '4季度：开始新的生产', checked: false, module: 'quarter4' },
  { name: '4季度：更新应收款/应收款收现', checked: false, module: 'quarter4' },
  { name: '4季度：交货给客户', checked: false, module: 'quarter4' },
  { name: '4季度：产品研发投资', checked: false, module: 'quarter4' },
  { name: '4季度：支付行政管理费用', checked: false, module: 'quarter4' },







  // 年终


  { name: '更新长期贷款/支付利息', checked: false, module: 'yearEnd' },
  { name: '支付设备维修费用', checked: false, module: 'yearEnd' },
  { name: '支付租金', checked: false, module: 'yearEnd' },
  { name: '新入准市场/ISO认证投资', checked: false, module: 'yearEnd' },
  { name: '关账', checked: false, module: 'yearEnd' }
])

const userInfo = ref({
  gameId: '',
  username: ''
})
// 从localStorage获取用户信息
const storedUser = JSON.parse(localStorage.getItem('userInfo') || '{}')
userInfo.value = {
  gameId: storedUser.gameId || '',
  username: storedUser.username || ''
}

const countdown = ref(0)
const showCountdown = ref(false)
let countdownTimer = null
const isGameStarted = ref(false)

// 添加广告弹窗状态
const showAdModal = ref(false)
const adData = ref([
  [0, 0, 0, 0, 0], // P1
  [0, 0, 0, 0, 0], // P2
  [0, 0, 0, 0, 0], // P3
  [0, 0, 0, 0, 0]  // P4
])

// 在data部分添加消息列表
const messages = ref([])

// 在data部分添加准备状态
const isReady = ref(false)
const players = ref([])


const timeLine = ref('第1年 第1季')

// 添加新的响应式变量
const totalPlayers = ref(1)
const maxPlayers = ref(8)

// 在data部分添加全局进度
const globalProgress = ref(0)

const orderRegistrationModal = ref()

// 在setup部分添加currentGameId的获取
const currentGameId = ref(route.query.gameId || userInfo.value.gameId)

function openModal(content) {
  modalContent.value = content
  showModal.value = true
}

function closeModal() {
  showModal.value = false
}

function handleClick(name) {
  if (name === '退出') {
    handleLogout()
  } else {
    alert(`Clicked: ${name}`)
  }
}

function handleLogout() {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.close()
  }
  router.push('/login').then(() => {
    window.location.reload()
  })
}

const validateCheck = (index) => {
  const previousUnchecked = globalTasks.value
    .slice(0, index)
    .some(t => !t.checked)

  if (previousUnchecked) {
    alert('请按顺序完成前面的任务')
    return false
  }
  return true
}

const handleTaskChange = (index) => {
  if (!isGameStarted.value) {
    alert('游戏尚未开始，不能进行操作')
    globalTasks.value[index].checked = false
    return
  }

  // 处理需要弹窗的任务（索引0、3、4）
  if ([0, 3, 4].includes(index)) {
    showCustomModal.value = true
    currentTaskIndex.value = index
    return
  }

  // 处理广告投放（索引1）
  if (index === 1) {
    showAdModal.value = true
    currentTaskIndex.value = index
    return
  }

  // 处理登记销售订单（索引2）
  if (index === 2) {
    orderRegistrationModal.value.show(userInfo.value.gameId)
    return
  }

  if (!globalTasks.value[index].checked) {
    globalTasks.value.forEach((t, i) => {
      if (i > index) t.checked = false
    })
    return
  }

  if (!validateCheck(index)) {
    globalTasks.value[index].checked = false
  }
}

// 添加新的弹窗状态
const showCustomModal = ref(false)
const currentTaskIndex = ref(-1)
const customModalContent = `
挑战！

下面是针对在不久的将来，市场发展的一些预测。这些预测源自一家声誉良好的市场调研机构，它提供了针对市场发展前景的高质量的估计，可为投资决策提供依据，但是没有人会为此估计的结果担保。

产品：
P1产品是一个著名的产品，它在不久的将来面临激烈的竞争，无论是来自于当地的"同仁"，还是来自于丝毫不亚于当地"同仁"的外国竞争者。这些外国竞争者能够更经济的生产。
P2产品是一个P1产品的技术改进版，是下一步的自然发展方向。P2产品可望补偿针对P1产品需求的下降。
P3产品是一个远远领先的新技术产品，被视为未来技术上及有利于环保方面的一个飞跃。目前很难评估客户针对这种新技术的态度。
P4产品被视为一个未来技术的产品，针对它，大家都存在着期望，然而它的市场何时才能形成是一个难题。

市场：
本地市场针对P1产品的需求已经减弱，但是在不久的将来，仍然存在着对P1的不少需求。为了弥补这个市场的下降，新的市场或许存在着机遇。
开始阶段，或许可以在企业周边的区域（区域市场和国内市场），那里针对低技术产品（P1产品和P2产品）需求估计会很不错。这两个市场的需求量有很大的差别：以产品数量计，国内市场与本地市场相等，区域市场估计只有本地市场的一半。
亚洲市场的建立需要很长时间，大约为三年。因此针对其需求量的预测自然很不确定。这个市场被认为相当大，并且偏好高技术含量的产品。在这个市场上可以销售低技术产品，但是价格竞争会非常激烈。
进入国际市场可以在本期预测的时间段完成。这个市场估计会偏向于低技术产品，同时也存在着随机的可能性在后期可以销出技术更先进的产品。
进入一个市场意味着建立一些销售机构，它们可以销售企业所生产的产品。企业生产部分将永远不会移至国外。
预测显示的是市场上的全部需求量，也就是本地制造商可以得到的全部市场的份额。这个市场份额估计为全球市场需求量的10%，外国竞争者将分得剩余的90%。

祝创业者好运！
`

// 添加新的弹窗内容变量
const annualPlanContent = `
整体战略方面
    评估内部资源与外部环境，制定长、中短期策略
    预测市场趋势、调整既定战略
产品研发方面
    产品研发决策
    必要时做出修改研发计划，甚至中断项目决定
生产方面
    选择获取生产能力的方式（购买或租赁）
    设备更新与生产线改良
    全盘生产流程调度决策；匹配市场需求、交货期和数量及设备产能
    库存管理及产销配合
    必要时选择清偿生产能力的方式
市场营销与销售方面
    市场开发决策
    新产品开发、产品组合与市场定位决策
    模拟在市场中短兵相接的竞标过程
    刺探同行敌情，抢攻市场
    建立并维护市场地位、必要时做退出市场决策
财务方面
    制定投资计划，评估应收账款金额与回收期
    预估长、短期资金需求，寻求资金来源
    掌握资金来源与用途，妥善控制成本
    洞悉资金短缺前兆，以最佳方式筹措资金
分析财务报表、掌握报表重点与数据含义
    运用财务指标进行内部诊断，协助管理决策
    如何以有限资金转亏为盈、创造高利润
    编制财务报表、结算投资报酬、评估决策效益 
团队协作与沟通方面
    实地学习如何在立场不同的个部门间沟通协调
    培养不同部门人员的共同价值观与经营理念
    建立以整体利益为导向的组织
`

// 添加税务说明内容
const taxPaymentContent = `
当您经营累计的利润留存为正数时，系统将按国家规定计算当年税前利润(为正数时)的25%作为所得税，
税金在下一年执行"支付税金项"时，系统自动扣除。
`

// 添加确认回调函数
const handleConfirm = () => {
  globalTasks.value[currentTaskIndex.value].checked = true
  showCustomModal.value = false
  validateCheck(currentTaskIndex.value)
  sendTaskComplete(globalTasks.value[currentTaskIndex.value].name)
}

// 添加取消回调函数
const handleCancel = () => {
  showCustomModal.value = false
}

// 修改广告取消函数
const cancelAd = () => {
  showAdModal.value = false
  // 重置广告数据并取消勾选
  adData.value = adData.value.map(row => row.map(() => 0))
  globalTasks.value[currentTaskIndex.value].checked = false
}

// 修改广告确认函数
const handleSaveAds = async () => {
  try {
    // 收集非零广告数据
    const adList = adData.value.flatMap((row, productIndex) => 
      row.map((amount, regionIndex) => ({
        region: ['本地', '区域', '国内', '亚洲', '国际'][regionIndex],
        product: `P${productIndex + 1}`,
        amount
      })).filter(item => item.amount > 0)
    )

    if (adList.length === 0) {
      alert('请至少填写一个非零广告费用')
      return
    }

    const response = await axios.post(
      `${import.meta.env.VITE_API_BASE_URL}/api/game/save-ads`,
      {
        gameId: userInfo.value.gameId,
        username: userInfo.value.username,
        ads: adList
      }
    )

    if (response.data.code === 200) {
      globalTasks.value[currentTaskIndex.value].checked = true
      showAdModal.value = false
      sendTaskComplete(globalTasks.value[currentTaskIndex.value].name)
    } else {
      alert('保存失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('广告保存请求失败:', error)
    alert('网络异常：' + error.message)
  }
}

const updateSocketId = async (socketId) => {
  try {
    const response = await fetch(
      `${import.meta.env.VITE_API_BASE_URL}/api/users/updateSocketId`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          gameId: userInfo.value.gameId,
          username: userInfo.value.username,
          socketId: socketId
        })
      }
    )
    
    const data = await response.json()
    if (data.code !== 200) {
      console.error('更新socketId失败:', data.msg)
      alert('连接状态更新失败，部分功能可能受限')
    }
  } catch (error) {
    console.error('更新socketId请求失败:', error)
    alert('网络连接异常，请检查网络后重试')
  }
}

const fetchPlayers = async () => {
  try {
    const response = await fetch(
      `${import.meta.env.VITE_API_BASE_URL}/api/users/${userInfo.value.gameId}/players`
    )
    const data = await response.json()
    if (data.code === 200) {
      players.value = data.data
        .map(p => ({
          username: p.username,
          isReady: p.isReady
        }))
        .filter(p => p.username !== userInfo.value.username)
      totalPlayers.value = data.totalPlayers || 1
      maxPlayers.value = data.maxPlayers || 8
    }
  } catch (error) {
    console.error('获取玩家列表失败:', error)
  }
}

// 添加重连机制
const setupWebSocket = () => {
  socket = new WebSocket(
    import.meta.env.VITE_API_BASE_URL.replace('http', 'ws') + '/websocket'
  )
  
  socket.onopen = () => {
    console.log('WebSocket连接已打开')
    
    // 发送用户加入通知
    if (socket.readyState === WebSocket.OPEN) {
      try {
        socket.send(JSON.stringify({
          type: "userJoin",
          gameId: userInfo.value.gameId,
          username: userInfo.value.username,
          initialProgress: 0
        }))
      } catch (error) {
        console.error('发送用户加入消息失败:', error)
      }
    }
  }
  socket.onmessage = (event) => {
    const data = JSON.parse(event.data)
    console.log('收到消息:', data)
    
    if (data.type === 'socketId') {
      console.log('Received socketId:', data.socketId)
      // 调用更新接口将socketId与用户关联
      fetch(
        `${import.meta.env.VITE_API_BASE_URL}/api/users/updateSocketId`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            gameId: userInfo.value.gameId,
            username: userInfo.value.username,
            socketId: data.socketId
          })
        }
      )
      .then(response => response.json())
      .then(data => {
        if (data.code !== 200) {
          console.error('更新socketId失败:', data.msg)
        }
      })
      .catch(error => {
        console.error('更新socketId请求失败:', error)
      })
    } else if (data.type === 'countdown') {
      showCountdown.value = true
      countdown.value = data.remaining
      // 添加倒计时动画
      // this.$nextTick(() => {
      //   const countdownEl = document.querySelector('.countdown-number')
      //   if (countdownEl) {
      //     countdownEl.classList.add('pulse')
      //   }
      // })
    } else if (data.type === 'gameStart') {
      isGameStarted.value = true
      timeLine.value = '第1年 第1季'
      showCountdown.value = false
    } else if (data.type === 'system') {
      messages.value.push({
        type: 'system',
        content: data.content,
        timestamp: new Date().toLocaleTimeString()
      })
    } else if (data.type === 'task') {
      messages.value.push({
        type: 'task',
        content: data.content,
        timestamp: new Date().toLocaleTimeString()
      })
    } else if (data.type === 'playerStatus') {
      console.log('收到玩家状态变更通知:', data.players)
      fetchPlayers()
    } else if (data.type === 'progressUpdate') {
      globalProgress.value = data.globalProgress
    } else if (data.type === 'orderUpdate') {
      orderRegistrationModal.value?.refreshOrders()
    }
  }

  socket.onclose = () => {
    console.log('连接断开，5秒后重连...')
    setTimeout(setupWebSocket, 5000)
  }
  socket.onerror = (error) => {
    console.error('WebSocket错误:', error)
    alert('连接服务器失败，请检查网络后重试')
  }

}

onMounted(async () => {
  // 同步路由参数到localStorage
  if (route.query.gameId && route.query.username) {
    localStorage.setItem('userInfo', JSON.stringify({
      gameId: route.query.gameId,
      username: route.query.username
    }))
  }

  // 恢复游戏状态
  try {
    const res = await fetch(
      `${import.meta.env.VITE_API_BASE_URL}/api/game/${userInfo.value.gameId}/state?username=${userInfo.value.username}`
    )
    const data = await res.json()
    
    if (data.code === 200) {
      // 恢复个人状态
      if (data.data.personalState) {
        const state = data.data.personalState
        // 恢复任务状态
        if (state.tasks) {
          globalTasks.value = state.tasks
        }
        // 恢复时间线
        if (data.data.timeline) {
          timeLine.value = data.data.timeline
        }
      }
    }
  } catch (e) {
    console.error('恢复状态失败:', e)
  }

  // 初始化WebSocket连接
  setupWebSocket()
  fetchPlayers()
})

onBeforeUnmount(() => {
  if (socket) {
    socket.close()
  }
})

const startCountdown = () => {
  isGameStarted.value = true
  countdown.value = 10
  showCountdown.value = true
  
  clearInterval(countdownTimer)
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      showCountdown.value = false
      isGameStarted.value = false
      isReady.value = false
    }
  }, 1000)
}

// 添加准备按钮
const toggleReady = () => {
  if (isReady.value) return
  
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify({
      type: "toggleReady",
      gameId: userInfo.value.gameId,
      username: userInfo.value.username,
      isReady: true
    }))
    isReady.value = true
  }
}

// 添加时间线更新逻辑
const updateTimeLine = (data) => {
  timeLine.value = `第${data.year}年 第${data.quarter}季`;
}

// 在handleConfirm和confirmAd方法中添加进度更新
const updateProgress = (taskNumber) => {
  fetch(
    `${import.meta.env.VITE_API_BASE_URL}/api/users/updateTaskProgress`, 
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        gameId: userInfo.value.gameId,
        username: userInfo.value.username,
        progress: taskNumber
      })
    }
  );
}

// 修改sendTaskComplete方法
const sendTaskComplete = (taskName) => {
  // 获取任务序号（根据任务列表顺序）
  const taskNumber = globalTasks.value.findIndex(t => t.name === taskName) + 1
  
  // 发送进度更新请求
  fetch(
    `${import.meta.env.VITE_API_BASE_URL}/api/game/updateProgress`, 
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        gameId: userInfo.value.gameId,
        username: userInfo.value.username,
        progress: taskNumber
      })
    }
  )

  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify({
      type: "taskComplete",
      gameId: userInfo.value.gameId,
      username: userInfo.value.username,
      taskName: taskName,
      taskNumber: taskNumber, // 添加任务序号
      timestamp: new Date().toISOString()
    }))
  }
}

const handleOrderConfirm = (taskName) => {
  const taskIndex = globalTasks.value.findIndex(t => t.name === taskName)
  if (taskIndex !== -1) {
    globalTasks.value[taskIndex].checked = true
    sendTaskComplete(taskName)
  }
}
</script>

<template>
  <div class="dashboard">
    <div class="header">
      <h1>电子沙盘培训系统</h1>
    </div>
    <div v-if="showCountdown" class="countdown-overlay">
      <div class="countdown-box">
        <h2>游戏即将开始</h2>
        <div v-if="countdown > 0" class="countdown-number">{{ countdown }}</div>
        <p>请做好准备！</p>
      </div>
    </div>
    <div class="menu-bar">
      <div class="top-menu">
        <button @click="handleClick('台面信息')">台面信息</button>
        <button @click="handleClick('经营结果')">经营结果</button>
        <button @click="handleClick('经营业绩排名')">经营业绩排名</button>
        <button @click="handleClick('英雄榜')">英雄榜</button>
        <button @click="handleClick('申请贴现')">申请贴现</button>
        <button @click="handleClick('购买厂房')">购买厂房</button>
        <button @click="handleClick('出售厂房')">出售厂房</button>
        <button @click="handleClick('规则说明')">规则说明</button>
        <button @click="handleClick('关于')">关于</button>
      </div>
      <div class="bottom-menu">
        <div class="user-info-tooltip">
          <span style="color: #333;">
            当前用户：{{ userInfo.username }}
            <span class="player-count">({{ totalPlayers }}/{{ maxPlayers }})</span>
          </span>
          <div class="user-list">
            <div v-if="players.length === 0" class="empty-tip">暂无其他玩家</div>
            <div v-for="(player, index) in players" :key="index" class="user-item">
              {{ player.username }} 
              <span :class="['status-dot', { 'ready': player.isReady }]"></span>
            </div>
          </div>
        </div>
        <span style="margin-left: 20px; color: #333;">游戏ID：{{ userInfo.gameId }}</span>
        <div class="action-buttons">
          <button 
            :class="{ 'action-btn': true, 'ready': isReady, 'disabled': isGameStarted }"
            :disabled="isReady || isGameStarted"
            @click="!isGameStarted && toggleReady()"
          >
            {{ isGameStarted ? timeLine : (isReady ? '已准备' : '点击准备') }}
          </button>
          <button @click="handleClick('退出')">退出</button>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="left-panel">
        <div class="message-box">
          <h3>实时消息</h3>
          <div class="message-list">
            <div v-for="(msg, index) in messages" :key="index" 
                 class="message-item" :class="msg.type">
              <span class="timestamp">{{ msg.timestamp }}</span>
              {{ msg.content }}
            </div>
          </div>
        </div>
        <div class="financial-info">
          <h3>财务信息</h3>
          <div>现金：0M</div>
          <div>应收账款：0M</div>
          <div>短期贷款：0M</div>
          <div>长期贷款：0M</div>
        </div>
        <div class="production-info">
          <h3>生产资料</h3>
          <p>已具备1生产能力</p>
          <p>已具备2生产能力</p>
        </div>
        <div class="market-info">
          <h3>市场进入</h3>
          <p>已进入本地市场</p>
          <p>已进入国内市场</p>
        </div>
        <div class="iso-info">
          <h3>ISO认证</h3>
          <p>已获得ISO9000认证</p>
          <p>已获得ISO14000认证</p>
        </div>
      </div>
      <div class="right-panel">
        <div class="top-section">
          <h3>年初计划</h3>
          <div class="task-item" v-for="(task, index) in globalTasks.filter(t => t.module === 'annual')" 
               :key="'annual-'+index">
            <span>{{ task.name }}</span>
            <input 
              type="checkbox" 
              :checked="task.checked" 
              @click="(e) => {
                const taskIndex = globalTasks.indexOf(task)
                e.preventDefault() // 阻止默认勾选行为
                handleTaskChange(taskIndex)
              }" 
              class="task-checkbox"
              :disabled="!isGameStarted || (globalTasks.indexOf(task) > 0 && !globalTasks[globalTasks.indexOf(task)-1].checked)
                        || (globalProgress >= 0 && globalTasks.indexOf(task) > globalProgress)
                        || task.checked"
            >
          </div>
        </div>

        <div class="middle-section">
          <h3>1季度进度</h3>
          <div class="task-item" v-for="(task, index) in globalTasks.filter(t => t.module === 'quarter1')" 
               :key="'quarter1-'+index">
            <span>{{ task.name }}</span>
            <input 
              type="checkbox" 
              :checked="task.checked" 
              @click="(e) => {
                const taskIndex = globalTasks.indexOf(task)
                // 添加对第二个任务的处理
                if (taskIndex === 0 || taskIndex === 1) {
                  e.preventDefault() // 阻止默认勾选行为
                  handleTaskChange(taskIndex)
                } else {
                  task.checked = e.target.checked;
                  handleTaskChange(taskIndex)
                }
              }" 
              class="task-checkbox"
              :disabled="!isGameStarted || (globalTasks.indexOf(task) > 0 && !globalTasks[globalTasks.indexOf(task)-1].checked)
              || (globalProgress >= 0 && globalTasks.indexOf(task) > globalProgress)
              || task.checked"
            >
          </div>
        </div>

        <div class="middle-section">
          <h3>2季度进度</h3>
          <div class="task-item" v-for="(task, index) in globalTasks.filter(t => t.module === 'quarter2')" 
               :key="'quarter2-'+index">
            <span>{{ task.name }}</span>
            <input 
              type="checkbox" 
              :checked="task.checked" 
              @click="(e) => {
                const taskIndex = globalTasks.indexOf(task)
                // 添加对第二个任务的处理
                if (taskIndex === 0 || taskIndex === 1) {
                  e.preventDefault() // 阻止默认勾选行为
                  handleTaskChange(taskIndex)
                } else {
                  task.checked = e.target.checked;
                  handleTaskChange(taskIndex)
                }
              }" 
              class="task-checkbox"
              :disabled="!isGameStarted || (globalTasks.indexOf(task) > 0 && !globalTasks[globalTasks.indexOf(task)-1].checked)
              || (globalProgress >= 0 && globalTasks.indexOf(task) > globalProgress)
              || task.checked"
            >
          </div>
        </div>

        <div class="middle-section">
          <h3>3季度进度</h3>
          <div class="task-item" v-for="(task, index) in globalTasks.filter(t => t.module === 'quarter3')" 
               :key="'quarter3-'+index">
            <span>{{ task.name }}</span>
            <input 
              type="checkbox" 
              :checked="task.checked" 
              @click="(e) => {
                const taskIndex = globalTasks.indexOf(task)
                // 添加对第二个任务的处理
                if (taskIndex === 0 || taskIndex === 1) {
                  e.preventDefault() // 阻止默认勾选行为
                  handleTaskChange(taskIndex)
                } else {
                  task.checked = e.target.checked;
                  handleTaskChange(taskIndex)
                }
              }" 
              class="task-checkbox"
              :disabled="!isGameStarted || (globalTasks.indexOf(task) > 0 && !globalTasks[globalTasks.indexOf(task)-1].checked)
              || (globalProgress >= 0 && globalTasks.indexOf(task) > globalProgress)
              || task.checked"
            >
          </div>
        </div>

        <div class="middle-section">
          <h3>4季度进度</h3>
          <div class="task-item" v-for="(task, index) in globalTasks.filter(t => t.module === 'quarter4')" 
               :key="'quarter4-'+index">
            <span>{{ task.name }}</span>
            <input 
              type="checkbox" 
              :checked="task.checked" 
              @click="(e) => {
                const taskIndex = globalTasks.indexOf(task)
                // 添加对第二个任务的处理
                if (taskIndex === 0 || taskIndex === 1) {
                  e.preventDefault() // 阻止默认勾选行为
                  handleTaskChange(taskIndex)
                } else {
                  task.checked = e.target.checked;
                  handleTaskChange(taskIndex)
                }
              }" 
              class="task-checkbox"
              :disabled="!isGameStarted || (globalTasks.indexOf(task) > 0 && !globalTasks[globalTasks.indexOf(task)-1].checked)
              || (globalProgress >= 0 && globalTasks.indexOf(task) > globalProgress)
              || task.checked"
            >
          </div>
        </div>

        <div class="bottom-section">
          <h3>年终</h3>
          <div class="task-item" v-for="(task, index) in globalTasks.filter(t => t.module === 'yearEnd')" 
               :key="'year-'+index">
            <span>{{ task.name }}</span>
            <input 
              type="checkbox" 
              :checked="task.checked" 
              @click="(e) => {
                const taskIndex = globalTasks.indexOf(task)
                // 添加对第二个任务的处理
                if (taskIndex === 0 || taskIndex === 1) {
                  e.preventDefault() // 阻止默认勾选行为
                  handleTaskChange(taskIndex)
                } else {
                  task.checked = e.target.checked;
                  handleTaskChange(taskIndex)
                }
              }" 
              class="task-checkbox"
              :disabled="!isGameStarted || (globalTasks.indexOf(task) > 0 && !globalTasks[globalTasks.indexOf(task)-1].checked)
              || (globalProgress >= 0 && globalTasks.indexOf(task) > globalProgress)
              || task.checked"
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <div v-if="showModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <p>{{ modalContent }}</p>
      </div>
    </div>
    <!-- 添加新的弹窗 -->
    <div v-if="showCustomModal" class="custom-modal">
      <div class="custom-modal-content">
        <div class="modal-header">
          <h3>
            {{ 
              currentTaskIndex === 0 ? '新年度规划会议' : 
              currentTaskIndex === 3 ? '制定新年度计划' : '支付应付税'
            }}
          </h3>
          <button class="close" @click="handleCancel">&times;</button>
        </div>
        <div class="modal-body">
          <pre>
            {{
              currentTaskIndex === 0 ? customModalContent : 
              currentTaskIndex === 3 ? annualPlanContent : taxPaymentContent
            }}
          </pre>
        </div>
        <div class="modal-footer">
          <button @click="handleConfirm" class="confirm-btn">确定</button>
          <button @click="handleCancel" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
    <!-- 添加广告弹窗 -->
    <div v-if="showAdModal" class="custom-modal">
      <div class="custom-modal-content">
        <div class="modal-header">
          <h3>广告投放</h3>
          <span class="close" @click="cancelAd">×</span>
        </div>
        <div class="modal-body">
          <table class="ad-table">
            <tr>
              <th>产品/市场</th>
              <th>本地</th>
              <th>区域</th>
              <th>国内</th>
              <th>亚洲</th>
              <th>国际</th>
            </tr>
            <tr v-for="(row, index) in adData" :key="index">
              <td>P{{ index + 1 }}</td>
              <td v-for="(cell, cellIndex) in row" :key="cellIndex">
                <input 
                  type="number" 
                  class="ad-input" 
                  v-model.number="adData[index][cellIndex]"
                  min="0"
                >
                <span class="unit">M</span>
              </td>
            </tr>
          </table>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="cancelAd">取消</button>
          <button class="confirm-btn" @click="handleSaveAds">确认</button>
        </div>
      </div>
    </div>
    <!-- 在模板顶部添加进度显示 -->
    <div class="progress-bar">
      本年度进度：任务 {{ globalProgress }}
      <div class="progress-track">
        <div class="progress-fill" :style="{ width: (globalProgress / globalTasks.length) * 100 + '%' }"></div>
      </div>
    </div>
    <OrderRegistrationModal 
      ref="orderRegistrationModal"
      @confirm="handleOrderConfirm"
    />
  </div>
</template>

<style scoped>
.header {
  background-color: #ffffff;
  padding: 15px 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header h1 {
  margin: 0;
  color: #007bff;
  font-size: 24px;
  text-align: center;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}

.dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  padding-top: 10px; /* 减少顶部内边距 */
}

.menu-bar {
  display: block;
  padding: 10px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  position: sticky;
  top: 0;
  z-index: 1000;
  background: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.top-menu {
  margin-bottom: 10px;
}

.top-menu button {
  margin-right: 8px;
}

.bottom-menu {
  display: flex;
  align-items: center;
  gap: 20px;
  padding-top: 10px;
  border-top: 1px solid #eee;
  justify-content: space-between;
}

.action-buttons {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.user-info-tooltip span {
  color: #333; /* 深灰色字体 */
  font-weight: 500;
}

button {
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 10px 15px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #0056b3;
}

.content {
  display: flex;
  gap: 30px; /* 增加左右面板间距 */
  margin-top: 20px;
}

.left-panel {
  flex: 1;
  margin-right: 20px;
  position: relative;
}

.right-panel {
  flex: 2;
}

.financial-info, .production-info, .market-info, .iso-info,
.top-section, .middle-section, .bottom-section {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  color: #000000; /* 黑色字体 */
  width: 500px; /* 固定宽度 */
}

h3 {
  margin-top: 0;
  color: #007bff;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  width: 300px;
  text-align: center;
}

.close {
  position: absolute;
  top: 10px;
  right: 20px;
  font-size: 24px;
  cursor: pointer;
  color: #007bff;
}

.logout-btn {
  position: fixed;
  top: 10px;
  right: 20px;
  padding: 8px 16px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  z-index: 1001;
}

.logout-btn:hover {
  background-color: #c82333;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.task-checkbox {
  margin-left: 10px;
  transform: scale(1.2);
  cursor: pointer;
}

.task-checkbox:checked {
  accent-color: #007bff;
}

.task-checkbox:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.task-checkbox:disabled + span {
  color: #999;
}

.countdown-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.countdown-box {
  background: white;
  padding: 2rem 4rem;
  border-radius: 15px;
  text-align: center;
  box-shadow: 0 0 20px rgba(0, 123, 255, 0.5);
}

.countdown-number {
  font-size: 5rem;
  font-weight: bold;
  color: #007bff;
  margin: 1rem 0;
  text-shadow: 0 0 10px rgba(0, 123, 255, 0.5);
}

.countdown-box h2 {
  color: #333;
  margin-bottom: 1rem;
}

.countdown-box p {
  color: #666;
  font-size: 1.2rem;
}

/* 调整系统信息模块间距 */
.financial-info {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

/* 保持其他信息模块的间距 */
.production-info,
.market-info,
.iso-info {
  margin-bottom: 25px;
}

/* 添加延伸分割线的伪元素 */
.left-panel::after {
  content: '';
  position: absolute;
  top: 0;
  right: -2px;
  height: 100%;
  width: 2px;
  background-color: #007bff;
  z-index: 1;
}

/* 添加新的弹窗样式 */
.custom-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2001;
}

.custom-modal-content {
  background: linear-gradient(145deg, #007bff, #0056b3);
  border-radius: 10px;
  width: 800px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 0 20px rgba(0,123,255,0.3);
}

.modal-header {
  padding: 20px;
  background: rgba(0,0,0,0.1);
  border-bottom: 1px solid rgba(255,255,255,0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  color: white;
  margin: 0;
}

.modal-body {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
  background: rgba(255,255,255,0.95);
}

.modal-body pre {
  white-space: pre-wrap;
  font-family: 'Microsoft YaHei', sans-serif;
  line-height: 1.6;
  color: #333;
}

.modal-footer {
  padding: 15px 20px;
  background: rgba(0,0,0,0.1);
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.confirm-btn, .cancel-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.confirm-btn {
  background-color: #28a745;
  color: white;
}

.confirm-btn:hover {
  background-color: #218838;
}

.cancel-btn {
  background-color: #dc3545;
  color: white;
}

.cancel-btn:hover {
  background-color: #c82333;
}

.close {
  color: white;
  font-size: 28px;
  cursor: pointer;
  transition: color 0.3s;
}

.close:hover {
  color: #ffdd00;
}

/* 添加广告表格样式 */
.ad-table {
  width: 100%;
  border-collapse: collapse;
  margin: 10px 0;
}

.ad-table th, .ad-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}

.ad-table th {
  background-color: #007bff;
  color: white;
}

.ad-table td:first-child {
  background-color: #007bff;
  color: white;
}

.ad-table tr:nth-child(even) {
  background-color: #f2f2f2;
}

.ad-input {
  width: 60px;
  padding: 4px;
  border: 1px solid #ccc;
  border-radius: 4px;
  text-align: right;
}

.unit {
  margin-left: 4px;
  color: #666;
}

.message-box {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  max-height: 300px;
  overflow-y: auto;
  color: #000;
}

.message-list {
  max-height: 250px;
  overflow-y: auto;
}

.message-item {
  padding: 8px;
  margin: 5px 0;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000;
}

.message-item.system {
  background-color: #e3f2fd;
  border-left: 4px solid #2196f3;
  color: #1a237e;
}

.message-item.task {
  background-color: #f0f4c3;
  border-left: 4px solid #cddc39;
  color: #827717;
}

.timestamp {
  font-size: 0.8em;
  color: #666;
  margin-right: 10px;
}

/* 添加准备按钮样式 */
.action-btn {
  background-color: #6c757d;
  min-width: 120px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-btn.disabled {
  background-color: #17a2b8;
  cursor: default;
}

.action-btn.ready {
  background-color: #28a745;
}

.user-info-tooltip {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.user-info-tooltip:hover .user-list {
  visibility: visible;
  opacity: 1;
}

.user-list {
  position: absolute;
  bottom: 100%;
  left: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  min-width: 150px;
  z-index: 1000;
  visibility: hidden;
  opacity: 0;
  transition: opacity 0.3s;
  color: #333;
}

.user-item {
  padding: 5px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #333;
}

.status-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #dc3545; /* 未准备状态 */
}

.status-dot.ready {
  background-color: #28a745; /* 已准备状态 */
}

.player-count {
  font-size: 0.8em;
  color: #666;
  margin-left: 5px;
}

.empty-tip {
  color: #999;
  font-size: 0.9em;
  text-align: center;
  padding: 10px 0;
}

.pulse {
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

/* 在样式中添加 */
.progress-bar {
  margin: 20px 0;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  color: #000;
}

.progress-track {
  height: 10px;
  background: #eee;
  border-radius: 5px;
  margin-top: 10px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #007bff;
  transition: width 0.3s ease;
}
</style> 